package p2pcdnsim.network;

import p2pcdnsim.exception.PortAlreadyInUseException;
import desmoj.core.simulator.Model;
import desmoj.core.simulator.SimProcess;


public abstract class ApplicationProcess extends SimProcess {
	
	protected ApplicationLayer appLayer;
	protected NetworkAddress address;

	public ApplicationProcess(Model owner, String name) {
		super(owner, name, true);
	}

	@Override
	public void lifeCycle() {
		run();
	}

	
	protected abstract void run();

	protected ServerSocket createServerSocket(int port) throws PortAlreadyInUseException {
		return appLayer.createServerSocket(this, port);
	}

	protected DatagramSocket createDatagramSocket(int port) throws PortAlreadyInUseException {
		return appLayer.createDatagramSocket(this, port);
	}

	protected DatagramSocket createDatagramSocket() {
		return appLayer.createDatagramSocket(this);
	}
	
	public void setApplicationLayer(ApplicationLayer applicationLayer) {
		this.appLayer = applicationLayer;
		this.address = this.appLayer.getTransportLayer().getNetworkLayer().getDefaultAddress();
	}
	
	protected Socket createSocket(NetworkAddress address, int port) throws PortAlreadyInUseException {
		return appLayer.createSocket(this, address, port);
	}

	protected ApplicationLayer getApplicationLayer() {
		return appLayer;
	}
	
	public NetworkAddress getNetworkAddress() {
		return address;
	}
	
	public void setNetworkAddress(NetworkAddress address) {
		this.address = address;
	}
}
